/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Department;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class DepartmentBean implements DepartmentLocal {
    @EJB
    private ContactableLocal contactableBean;

    @PersistenceContext
    private EntityManager em;

    public Department findDepartment(KeyLocal key, Long departmentId) {
        Department department = em.find(Department.class, departmentId);
        key.assertHasPermission(department, Permission.NODE_VIEW);
        return department;
    }

    public Department createDepartment(KeyLocal key, Department department) {
        key.assertHasPermission(department.getParentNode(), Permission.DEPARTMENT_CREATE);
        ChangeDelta changeDelta = department.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        contactableBean.logCreate(department, changeDelta);
        em.persist(department);
        em.persist(changeDelta);
        return department;
    }

    public void editDepartment(KeyLocal key, Department department) {
        Department current = em.find(Department.class, department.getId());
        key.assertHasPermission(department, Permission.DEPARTMENT_EDIT);
        ChangeDelta changeDelta = department.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        contactableBean.logEdit(department, current, changeDelta);
        em.persist(changeDelta);
        em.merge(department);
    }

    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method" or "Web Service > Add Operation")
 
}
